// debugTools.js - 性能监控和调试工具系统
import { reactive, ref, computed } from 'vue'

/**
 * 性能监控器 - 监控3D渲染性能
 */
export class PerformanceMonitor {
    constructor() {
        this.stats = reactive({
            // 帧率统计
            fps: 0,
            frameTime: 0,
            averageFPS: 0,
            minFPS: Infinity,
            maxFPS: 0,

            // 渲染统计
            drawCalls: 0,
            triangles: 0,
            vertices: 0,
            textures: 0,

            // 内存统计
            totalMemory: 0,
            usedMemory: 0,
            geometryMemory: 0,
            textureMemory: 0,

            // GPU统计
            gpuInfo: {
                vendor: '',
                renderer: '',
                version: '',
                extensions: []
            },

            // 时间统计
            renderTime: 0,
            uploadTime: 0,
            cpuTime: 0,

            // 警告和错误
            warnings: [],
            errors: []
        })

        this.history = {
            fps: [],
            frameTime: [],
            drawCalls: [],
            memory: []
        }

        this.frameCount = 0
        this.lastTime = performance.now()
        this.fpsUpdateInterval = 1000 // 每秒更新一次FPS
        this.fpsLastUpdate = 0

        this.isRecording = false
        this.maxHistoryLength = 300 // 保持5分钟的历史数据（60fps）
    }

    /**
     * 初始化监控器
     */
    initialize(gl) {
        this.gl = gl
        this.collectGPUInfo(gl)
        this.startMonitoring()
    }

    /**
     * 收集GPU信息
     */
    collectGPUInfo(gl) {
        const debugInfo = gl.getExtension('WEBGL_debug_renderer_info')

        this.stats.gpuInfo = {
            vendor: debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : 'Unknown',
            renderer: debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : 'Unknown',
            version: gl.getParameter(gl.VERSION),
            extensions: gl.getSupportedExtensions() || []
        }

        // 获取WebGL限制
        this.stats.limits = {
            maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
            maxVertexAttribs: gl.getParameter(gl.MAX_VERTEX_ATTRIBS),
            maxVertexUniformVectors: gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS),
            maxFragmentUniformVectors: gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS),
            maxVaryingVectors: gl.getParameter(gl.MAX_VARYING_VECTORS)
        }
    }

    /**
     * 开始监控
     */
    startMonitoring() {
        this.isRecording = true
        this.monitoringLoop()
    }

    /**
     * 停止监控
     */
    stopMonitoring() {
        this.isRecording = false
    }

    /**
     * 监控循环
     */
    monitoringLoop() {
        if (!this.isRecording) return

        const currentTime = performance.now()
        const deltaTime = currentTime - this.lastTime

        // 更新帧时间
        this.stats.frameTime = deltaTime
        this.frameCount++

        // 更新FPS（每秒更新一次）
        if (currentTime - this.fpsLastUpdate >= this.fpsUpdateInterval) {
            const fps = Math.round(this.frameCount * 1000 / (currentTime - this.fpsLastUpdate))
            this.stats.fps = fps
            this.stats.minFPS = Math.min(this.stats.minFPS, fps)
            this.stats.maxFPS = Math.max(this.stats.maxFPS, fps)

            // 计算平均FPS
            this.history.fps.push(fps)
            if (this.history.fps.length > 60) { // 保持最近60秒的数据
                this.history.fps.shift()
            }
            this.stats.averageFPS = Math.round(
                this.history.fps.reduce((a, b) => a + b, 0) / this.history.fps.length
            )

            this.frameCount = 0
            this.fpsLastUpdate = currentTime
        }

        // 更新历史数据
        this.updateHistory()

        // 检查性能警告
        this.checkPerformanceWarnings()

        this.lastTime = currentTime

        // 继续监控
        requestAnimationFrame(() => this.monitoringLoop())
    }

    /**
     * 更新历史数据
     */
    updateHistory() {
        const currentTime = Date.now()

        // 添加到历史记录
        this.addToHistory('frameTime', { time: currentTime, value: this.stats.frameTime })
        this.addToHistory('drawCalls', { time: currentTime, value: this.stats.drawCalls })
        this.addToHistory('memory', { time: currentTime, value: this.stats.usedMemory })
    }

    /**
     * 添加到历史记录
     */
    addToHistory(type, data) {
        if (!this.history[type]) this.history[type] = []

        this.history[type].push(data)

        if (this.history[type].length > this.maxHistoryLength) {
            this.history[type].shift()
        }
    }

    /**
     * 检查性能警告
     */
    checkPerformanceWarnings() {
        const warnings = []

        // FPS过低警告
        if (this.stats.fps < 30 && this.stats.fps > 0) {
            warnings.push({
                type: 'performance',
                level: 'warning',
                message: `FPS过低: ${this.stats.fps}fps`,
                suggestion: '考虑降低模型复杂度或禁用一些后处理效果'
            })
        }

        // 绘制调用过多警告
        if (this.stats.drawCalls > 100) {
            warnings.push({
                type: 'performance',
                level: 'warning',
                message: `绘制调用过多: ${this.stats.drawCalls}`,
                suggestion: '考虑合并几何体或使用实例化渲染'
            })
        }

        // 内存使用过高警告
        if (this.stats.usedMemory > 500 * 1024 * 1024) { // 500MB
            warnings.push({
                type: 'memory',
                level: 'warning',
                message: `内存使用过高: ${this.formatBytes(this.stats.usedMemory)}`,
                suggestion: '考虑压缩纹理或降低模型精度'
            })
        }

        this.stats.warnings = warnings
    }

    /**
     * 开始帧测量
     */
    beginFrame() {
        this.frameStartTime = performance.now()
        this.stats.drawCalls = 0
        this.stats.triangles = 0
    }

    /**
     * 结束帧测量
     */
    endFrame() {
        if (this.frameStartTime) {
            this.stats.renderTime = performance.now() - this.frameStartTime
        }
    }

    /**
     * 记录绘制调用
     */
    recordDrawCall(triangleCount = 0, vertexCount = 0) {
        this.stats.drawCalls++
        this.stats.triangles += triangleCount
        this.stats.vertices += vertexCount
    }

    /**
     * 记录内存使用
     */
    recordMemoryUsage(geometryMemory = 0, textureMemory = 0) {
        this.stats.geometryMemory = geometryMemory
        this.stats.textureMemory = textureMemory
        this.stats.usedMemory = geometryMemory + textureMemory
    }

    /**
     * 添加错误
     */
    addError(error, context = '') {
        this.stats.errors.push({
            timestamp: Date.now(),
            message: error.message,
            context,
            stack: error.stack
        })

        // 只保留最近的100个错误
        if (this.stats.errors.length > 100) {
            this.stats.errors.shift()
        }
    }

    /**
     * 格式化字节
     */
    formatBytes(bytes) {
        if (bytes === 0) return '0 B'
        const k = 1024
        const sizes = ['B', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    /**
     * 导出性能报告
     */
    exportReport() {
        const report = {
            timestamp: new Date().toISOString(),
            summary: {
                averageFPS: this.stats.averageFPS,
                minFPS: this.stats.minFPS,
                maxFPS: this.stats.maxFPS,
                averageFrameTime: this.stats.frameTime,
                averageDrawCalls: this.stats.drawCalls,
                memoryUsage: this.stats.usedMemory
            },
            gpuInfo: this.stats.gpuInfo,
            limits: this.stats.limits,
            history: {
                fps: this.history.fps.slice(-60), // 最近60秒
                frameTime: this.history.frameTime.slice(-60),
                drawCalls: this.history.drawCalls.slice(-60),
                memory: this.history.memory.slice(-60)
            },
            warnings: this.stats.warnings,
            errors: this.stats.errors
        }

        return report
    }

    /**
     * 重置统计
     */
    reset() {
        this.stats.minFPS = Infinity
        this.stats.maxFPS = 0
        this.stats.warnings = []
        this.stats.errors = []

        Object.keys(this.history).forEach(key => {
            this.history[key] = []
        })
    }
}

/**
 * 调试可视化器 - 提供各种调试可视化
 */
export class DebugVisualizer {
    constructor(gl) {
        this.gl = gl
        this.enabled = false
        this.debugRenders = new Map()
        this.initializeDebugShaders()
    }

    /**
     * 初始化调试着色器
     */
    initializeDebugShaders() {
        const gl = this.gl

        // 线框着色器
        this.wireframeShader = this.createDebugShader(`
            precision mediump float;
            uniform vec3 u_color;
            void main() {
                gl_FragColor = vec4(u_color, 1.0);
            }
        `)

        // 法线可视化着色器
        this.normalShader = this.createDebugShader(`
            precision mediump float;
            varying vec3 v_normal;
            void main() {
                vec3 normal = normalize(v_normal) * 0.5 + 0.5;
                gl_FragColor = vec4(normal, 1.0);
            }
        `)

        // 深度可视化着色器
        this.depthShader = this.createDebugShader(`
            precision mediump float;
            uniform float u_near;
            uniform float u_far;
            varying float v_depth;
            
            float linearizeDepth(float depth) {
                float z = depth * 2.0 - 1.0;
                return (2.0 * u_near * u_far) / (u_far + u_near - z * (u_far - u_near));
            }
            
            void main() {
                float depth = linearizeDepth(gl_FragCoord.z) / u_far;
                gl_FragColor = vec4(vec3(depth), 1.0);
            }
        `)

        // UV坐标可视化着色器
        this.uvShader = this.createDebugShader(`
            precision mediump float;
            varying vec2 v_texCoord;
            void main() {
                gl_FragColor = vec4(v_texCoord, 0.0, 1.0);
            }
        `)
    }

    /**
     * 创建调试着色器
     */
    createDebugShader(fragmentSource) {
        const gl = this.gl

        const vertexSource = `
            attribute vec3 a_position;
            attribute vec3 a_normal;
            attribute vec2 a_texCoord;
            
            uniform mat4 u_modelViewMatrix;
            uniform mat4 u_projectionMatrix;
            uniform mat4 u_normalMatrix;
            
            varying vec3 v_normal;
            varying vec2 v_texCoord;
            varying float v_depth;
            
            void main() {
                vec4 worldPosition = u_modelViewMatrix * vec4(a_position, 1.0);
                gl_Position = u_projectionMatrix * worldPosition;
                
                v_normal = normalize((u_normalMatrix * vec4(a_normal, 0.0)).xyz);
                v_texCoord = a_texCoord;
                v_depth = gl_Position.z;
            }
        `

        // 创建着色器程序的逻辑（简化）
        return { vertexSource, fragmentSource }
    }

    /**
     * 启用调试模式
     */
    enable() {
        this.enabled = true
    }

    /**
     * 禁用调试模式
     */
    disable() {
        this.enabled = false
    }

    /**
     * 渲染包围盒
     */
    renderBoundingBox(model, color = [1, 1, 0]) {
        if (!this.enabled || !model.bounds) return

        const gl = this.gl
        const bounds = model.bounds

        // 创建包围盒几何体
        const vertices = new Float32Array([
            // 前面
            bounds.min[0], bounds.min[1], bounds.max[2],
            bounds.max[0], bounds.min[1], bounds.max[2],
            bounds.max[0], bounds.max[1], bounds.max[2],
            bounds.min[0], bounds.max[1], bounds.max[2],

            // 后面
            bounds.min[0], bounds.min[1], bounds.min[2],
            bounds.max[0], bounds.min[1], bounds.min[2],
            bounds.max[0], bounds.max[1], bounds.min[2],
            bounds.min[0], bounds.max[1], bounds.min[2]
        ])

        const indices = new Uint16Array([
            // 前面
            0, 1, 1, 2, 2, 3, 3, 0,
            // 后面
            4, 5, 5, 6, 6, 7, 7, 4,
            // 连接
            0, 4, 1, 5, 2, 6, 3, 7
        ])

        // 渲染线框
        this.renderWireframe(vertices, indices, color)
    }

    /**
     * 渲染坐标轴
     */
    renderAxes(length = 1.0) {
        if (!this.enabled) return

        const vertices = new Float32Array([
            // X轴 (红色)
            0, 0, 0, length, 0, 0,
            // Y轴 (绿色)
            0, 0, 0, 0, length, 0,
            // Z轴 (蓝色)
            0, 0, 0, 0, 0, length
        ])

        const colors = [
            [1, 0, 0], // X轴 - 红色
            [0, 1, 0], // Y轴 - 绿色
            [0, 0, 1]  // Z轴 - 蓝色
        ]

        // 分别渲染三个轴
        for (let i = 0; i < 3; i++) {
            const axisVertices = vertices.slice(i * 6, (i + 1) * 6)
            this.renderLine(axisVertices, colors[i])
        }
    }

    /**
     * 渲染网格
     */
    renderGrid(size = 10, divisions = 10, color = [0.5, 0.5, 0.5]) {
        if (!this.enabled) return

        const vertices = []
        const step = size / divisions

        // 水平线
        for (let i = 0; i <= divisions; i++) {
            const z = -size / 2 + i * step
            vertices.push(-size / 2, 0, z, size / 2, 0, z)
        }

        // 垂直线
        for (let i = 0; i <= divisions; i++) {
            const x = -size / 2 + i * step
            vertices.push(x, 0, -size / 2, x, 0, size / 2)
        }

        this.renderLines(new Float32Array(vertices), color)
    }

    /**
     * 渲染法线
     */
    renderNormals(model, length = 0.1, color = [0, 1, 1]) {
        if (!this.enabled || !model.vertices || !model.normals) return

        const vertices = []

        for (let i = 0; i < model.vertices.length; i += 3) {
            const x = model.vertices[i]
            const y = model.vertices[i + 1]
            const z = model.vertices[i + 2]

            const nx = model.normals[i]
            const ny = model.normals[i + 1]
            const nz = model.normals[i + 2]

            // 起点
            vertices.push(x, y, z)
            // 终点
            vertices.push(x + nx * length, y + ny * length, z + nz * length)
        }

        this.renderLines(new Float32Array(vertices), color)
    }

    /**
     * 渲染线框
     */
    renderWireframe(vertices, indices, color) {
        // WebGL线框渲染实现
        console.log('渲染线框:', { vertices: vertices.length, indices: indices.length, color })
    }

    /**
     * 渲染单条线
     */
    renderLine(vertices, color) {
        console.log('渲染线:', { vertices, color })
    }

    /**
     * 渲染多条线
     */
    renderLines(vertices, color) {
        console.log('渲染多条线:', { vertices: vertices.length / 6, color })
    }

    /**
     * 截图
     */
    captureFrame() {
        const gl = this.gl
        const canvas = gl.canvas

        // 读取像素数据
        const pixels = new Uint8Array(canvas.width * canvas.height * 4)
        gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels)

        // 创建ImageData
        const imageData = new ImageData(new Uint8ClampedArray(pixels), canvas.width, canvas.height)

        // 翻转Y轴
        const flippedImageData = this.flipImageDataY(imageData)

        return flippedImageData
    }

    /**
     * 翻转ImageData的Y轴
     */
    flipImageDataY(imageData) {
        const { width, height, data } = imageData
        const flippedData = new Uint8ClampedArray(data.length)

        for (let y = 0; y < height; y++) {
            for (let x = 0; x < width; x++) {
                const srcIndex = (y * width + x) * 4
                const dstIndex = ((height - 1 - y) * width + x) * 4

                flippedData[dstIndex] = data[srcIndex]
                flippedData[dstIndex + 1] = data[srcIndex + 1]
                flippedData[dstIndex + 2] = data[srcIndex + 2]
                flippedData[dstIndex + 3] = data[srcIndex + 3]
            }
        }

        return new ImageData(flippedData, width, height)
    }

    /**
     * 清理资源
     */
    dispose() {
        this.debugRenders.clear()
    }
}

/**
 * 模型分析器 - 分析模型性能和质量
 */
export class ModelAnalyzer {
    constructor() {
        this.analysisResults = reactive({
            geometry: {
                vertexCount: 0,
                triangleCount: 0,
                hasNormals: false,
                hasUVs: false,
                hasColors: false,
                boundingBox: null,
                surfaceArea: 0,
                volume: 0
            },
            topology: {
                isWatertight: false,
                hasHoles: false,
                manifoldEdges: 0,
                nonManifoldEdges: 0,
                boundaryEdges: 0
            },
            performance: {
                memoryUsage: 0,
                renderComplexity: 'low',
                recommendations: []
            },
            quality: {
                score: 0,
                issues: []
            }
        })
    }

    /**
     * 分析模型
     */
    analyze(model) {
        this.analyzeGeometry(model)
        this.analyzeTopology(model)
        this.analyzePerformance(model)
        this.analyzeQuality(model)

        return this.analysisResults
    }

    /**
     * 分析几何信息
     */
    analyzeGeometry(model) {
        const geometry = this.analysisResults.geometry

        geometry.vertexCount = model.vertices ? model.vertices.length / 3 : 0
        geometry.triangleCount = model.indices ? model.indices.length / 3 : geometry.vertexCount / 3
        geometry.hasNormals = !!(model.normals && model.normals.length > 0)
        geometry.hasUVs = !!(model.uvs && model.uvs.length > 0)
        geometry.hasColors = !!(model.colors && model.colors.length > 0)
        geometry.boundingBox = model.bounds

        // 计算表面积和体积
        if (model.vertices && model.indices) {
            geometry.surfaceArea = this.calculateSurfaceArea(model)
            geometry.volume = this.calculateVolume(model)
        }
    }

    /**
     * 分析拓扑结构
     */
    analyzeTopology(model) {
        const topology = this.analysisResults.topology

        if (model.vertices && model.indices) {
            const edgeAnalysis = this.analyzeEdges(model)
            topology.manifoldEdges = edgeAnalysis.manifold
            topology.nonManifoldEdges = edgeAnalysis.nonManifold
            topology.boundaryEdges = edgeAnalysis.boundary
            topology.isWatertight = edgeAnalysis.boundary === 0
        }
    }

    /**
     * 分析性能
     */
    analyzePerformance(model) {
        const performance = this.analysisResults.performance

        // 计算内存使用
        let memoryUsage = 0
        if (model.vertices) memoryUsage += model.vertices.length * 4 // Float32
        if (model.normals) memoryUsage += model.normals.length * 4
        if (model.uvs) memoryUsage += model.uvs.length * 4
        if (model.indices) memoryUsage += model.indices.length * 2 // Uint16

        performance.memoryUsage = memoryUsage

        // 评估渲染复杂度
        const triangleCount = this.analysisResults.geometry.triangleCount
        if (triangleCount < 1000) {
            performance.renderComplexity = 'low'
        } else if (triangleCount < 10000) {
            performance.renderComplexity = 'medium'
        } else if (triangleCount < 100000) {
            performance.renderComplexity = 'high'
        } else {
            performance.renderComplexity = 'very-high'
        }

        // 生成建议
        performance.recommendations = this.generatePerformanceRecommendations()
    }

    /**
     * 分析质量
     */
    analyzeQuality(model) {
        const quality = this.analysisResults.quality
        let score = 100
        const issues = []

        // 检查是否有法向量
        if (!this.analysisResults.geometry.hasNormals) {
            score -= 20
            issues.push('缺少法向量数据')
        }

        // 检查是否有UV坐标
        if (!this.analysisResults.geometry.hasUVs) {
            score -= 10
            issues.push('缺少UV坐标')
        }

        // 检查拓扑问题
        if (this.analysisResults.topology.nonManifoldEdges > 0) {
            score -= 15
            issues.push(`存在${this.analysisResults.topology.nonManifoldEdges}条非流形边`)
        }

        // 检查是否封闭
        if (!this.analysisResults.topology.isWatertight) {
            score -= 10
            issues.push('模型不封闭（非水密）')
        }

        quality.score = Math.max(0, score)
        quality.issues = issues
    }

    /**
     * 计算表面积
     */
    calculateSurfaceArea(model) {
        if (!model.vertices || !model.indices) return 0

        let totalArea = 0
        const vertices = model.vertices
        const indices = model.indices

        for (let i = 0; i < indices.length; i += 3) {
            const i1 = indices[i] * 3
            const i2 = indices[i + 1] * 3
            const i3 = indices[i + 2] * 3

            const v1 = [vertices[i1], vertices[i1 + 1], vertices[i1 + 2]]
            const v2 = [vertices[i2], vertices[i2 + 1], vertices[i2 + 2]]
            const v3 = [vertices[i3], vertices[i3 + 1], vertices[i3 + 2]]

            const area = this.calculateTriangleArea(v1, v2, v3)
            totalArea += area
        }

        return totalArea
    }

    /**
     * 计算体积
     */
    calculateVolume(model) {
        if (!model.vertices || !model.indices) return 0

        let volume = 0
        const vertices = model.vertices
        const indices = model.indices

        // 使用散度定理计算体积
        for (let i = 0; i < indices.length; i += 3) {
            const i1 = indices[i] * 3
            const i2 = indices[i + 1] * 3
            const i3 = indices[i + 2] * 3

            const v1 = [vertices[i1], vertices[i1 + 1], vertices[i1 + 2]]
            const v2 = [vertices[i2], vertices[i2 + 1], vertices[i2 + 2]]
            const v3 = [vertices[i3], vertices[i3 + 1], vertices[i3 + 2]]

            // 计算三角形对体积的贡献
            volume += this.calculateTriangleVolume(v1, v2, v3)
        }

        return Math.abs(volume / 6)
    }

    /**
     * 计算三角形面积
     */
    calculateTriangleArea(v1, v2, v3) {
        const edge1 = [v2[0] - v1[0], v2[1] - v1[1], v2[2] - v1[2]]
        const edge2 = [v3[0] - v1[0], v3[1] - v1[1], v3[2] - v1[2]]

        const cross = [
            edge1[1] * edge2[2] - edge1[2] * edge2[1],
            edge1[2] * edge2[0] - edge1[0] * edge2[2],
            edge1[0] * edge2[1] - edge1[1] * edge2[0]
        ]

        const length = Math.sqrt(cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2])
        return length * 0.5
    }

    /**
     * 计算三角形对体积的贡献
     */
    calculateTriangleVolume(v1, v2, v3) {
        return v1[0] * (v2[1] * v3[2] - v2[2] * v3[1]) +
            v1[1] * (v2[2] * v3[0] - v2[0] * v3[2]) +
            v1[2] * (v2[0] * v3[1] - v2[1] * v3[0])
    }

    /**
     * 分析边
     */
    analyzeEdges(model) {
        const edges = new Map()
        const indices = model.indices

        // 统计边的出现次数
        for (let i = 0; i < indices.length; i += 3) {
            for (let j = 0; j < 3; j++) {
                const v1 = indices[i + j]
                const v2 = indices[i + (j + 1) % 3]

                const edgeKey = v1 < v2 ? `${v1}-${v2}` : `${v2}-${v1}`
                edges.set(edgeKey, (edges.get(edgeKey) || 0) + 1)
            }
        }

        let manifold = 0
        let nonManifold = 0
        let boundary = 0

        edges.forEach(count => {
            if (count === 1) boundary++
            else if (count === 2) manifold++
            else nonManifold++
        })

        return { manifold, nonManifold, boundary }
    }

    /**
     * 生成性能建议
     */
    generatePerformanceRecommendations() {
        const recommendations = []
        const triangleCount = this.analysisResults.geometry.triangleCount
        const memoryUsage = this.analysisResults.performance.memoryUsage

        if (triangleCount > 50000) {
            recommendations.push({
                type: 'optimization',
                message: '模型三角形数量过高',
                suggestion: '考虑使用LOD（细节层次）或简化算法减少多边形数量'
            })
        }

        if (memoryUsage > 10 * 1024 * 1024) { // 10MB
            recommendations.push({
                type: 'memory',
                message: '内存使用过高',
                suggestion: '考虑压缩几何数据或使用更高效的数据格式'
            })
        }

        if (!this.analysisResults.geometry.hasNormals) {
            recommendations.push({
                type: 'quality',
                message: '缺少法向量数据',
                suggestion: '生成平滑法向量以改善光照效果'
            })
        }

        return recommendations
    }

    /**
     * 导出分析报告
     */
    exportReport() {
        return {
            timestamp: new Date().toISOString(),
            analysis: { ...this.analysisResults }
        }
    }
}

/**
 * 调试控制面板Hook
 */
export function useDebugPanel() {
    const monitor = new PerformanceMonitor()
    const visualizer = new DebugVisualizer(null) // gl在初始化时设置
    const analyzer = new ModelAnalyzer()

    const debugConfig = reactive({
        showStats: true,
        showWireframe: false,
        showBoundingBox: false,
        showNormals: false,
        showGrid: true,
        showAxes: true,
        enablePerfMonitor: true,
        autoOptimize: false
    })

    const currentAnalysis = ref(null)

    // 初始化调试系统
    const initialize = (gl) => {
        monitor.initialize(gl)
        visualizer.gl = gl
        visualizer.enable()
    }

    // 分析当前模型
    const analyzeModel = (model) => {
        if (model) {
            currentAnalysis.value = analyzer.analyze(model)
        }
    }

    // 截图
    const captureFrame = () => {
        return visualizer.captureFrame()
    }

    // 导出性能报告
    const exportPerformanceReport = () => {
        return monitor.exportReport()
    }

    // 导出模型分析报告
    const exportModelReport = () => {
        return analyzer.exportReport()
    }

    return {
        // 状态
        debugConfig,
        currentAnalysis,
        performanceStats: computed(() => monitor.stats),

        // 方法
        initialize,
        analyzeModel,
        captureFrame,
        exportPerformanceReport,
        exportModelReport,

        // 实例
        monitor,
        visualizer,
        analyzer
    }
}